package com.jiao.store.service.impl;


import com.jiao.store.Vo.CartVO;
import com.jiao.store.entity.Card;
import com.jiao.store.entity.Product;
import com.jiao.store.mapper.CardMapper;
import com.jiao.store.mapper.ProductMapper;
import com.jiao.store.service.CardService;
import com.jiao.store.service.ex.InsertServiceException;
import com.jiao.store.service.ex.UpdateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class CardServiceImpl implements CardService {

    @Autowired
    private CardMapper cardmapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public void addToCard(Integer uid, Integer pid, Integer amount, String username) {

        //查询当前要添加的这个购物车，是否在表中已经存在了
        Card result = cardmapper.findByUidAndPid(uid, pid);
        if (result==null){ //表示当前商品从来没有加入，那就进行新增操作
            Card card=new Card();

           card.setUid(uid);
           card.setPid(pid);
           card.setNum(amount);
            Product product = productMapper.findById(pid);
            card.setPrice(product.getPrice());
            //补全日志
                card.setCreatUser(username);

                card.setCreatTime(new Date());

                card.setModifiedTime(new Date());
                card.setModifiedUser(username);

                Integer rows= cardmapper.insertCard(card);
                    if (rows==null){
                        throw  new InsertServiceException("插入数据时产生未知异常");
                    }
        }else { //表示当前商品已经在购物车，直接更改数量
            int num = result.getNum() + amount;
            Integer rows  = cardmapper.updateNumByCid(result.getCid(), num, username, new Date());
            if (rows !=1){
                throw new UpdateException("更新购物车产生未知异常");
            }
        }

    }

    @Override
    public List<CartVO> getVoByUid(Integer uid) {
        return cardmapper.findVoByUid(uid);
    }
}
